package com.qingzhuge.common.validator;


import com.google.common.collect.Maps;
import com.qingzhuge.exception.ValidatorException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Map;
import java.util.Set;

/**
 * @author : zero.xiao
 * @description : hibernate-validator校验工具类
 * 参考文档：http://docs.jboss.org/hibernate/validator/5.4/reference/en-US/html_single/
 * @date :2018/6/14 0014 下午 17:30
 * @since : 1.0.0
 * @modified :
 */
public class ValidatorUtil {
    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     * @param object        待校验对象
     * @param groups        待校验的组
     * @throws ValidatorException  校验不通过，则报ValidatorException异常
     */
    public static void validateEntity(Object object, Class<?>... groups)
            throws ValidatorException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            Map<String,Object> filed = Maps.newHashMap();
            for (ConstraintViolation<Object> violation : constraintViolations) {
                String message = violation.getMessage();
                String property = violation.getPropertyPath().toString();
                filed.put(property,message);
            }
            throw new ValidatorException(filed);
        }
    }
}
